<?php

namespace app\service;

use app\branch;
use app\message;
use app\model\CluePerson;
use app\model\SystemDynamicFromField;
use app\model\SystemFieldPower;
use app\model\SystemFieldRandPower;
use app\model\SystemMenu;
use app\model\UserOrganization;
use app\Request;
use app\stateData;
use think\Db;
use think\facade\Cache;
use app\model\User as UserModel;

class User
{
    /**
     * 获取当前用户字段权限
     * @param $user
     * @param $fid
     * @return array
     */
    public function userFieldPower($user,$fid,$uid): array
    {
        $systemFieldPower = new SystemFieldPower();
        $systemDynamicFromField = new SystemDynamicFromField();
        $systemFieldModel = new SystemFieldRandPower();
        $systemService = new System();
        $orgModel = new UserOrganization();
        //获取用户标示
        $id = $uid;

        $userData = $user->getIdUserData($id);

        //查询个人字段权限
        $fieldPower = $systemFieldPower->getUserFieldPower($userData['id'],stateData::$_power_from_identifying['people']);
        //查询角色字段权限
        $positionFieldPower = $systemFieldPower->getUserFieldPower($userData['level_id']['id'],stateData::$_power_from_identifying['position']);
        //查询公司字段权限
        //查询当前部门关联所有部门公司
        $orgStr = $systemService->getParentIdStr($userData['department_id']['id'],$orgModel->getStructure ());
        $orgArr = explode (',',rtrim ($orgStr,','));

        foreach ($orgArr as $value) {
            $companyFieldPower = $systemFieldPower->getUserFieldPower($value,stateData::$_power_from_identifying['organization']);
            if ($companyFieldPower){
                break;
            }
        }
        if (!empty($positionFieldPower) || !empty($companyFieldPower) || !empty($fieldPower)){

            $fieldData = array_unique(
                array_merge(
                    $fieldPower,
                    $positionFieldPower,
                    $companyFieldPower
                ),
                SORT_NUMERIC
            );

        }else{
            $fieldData = $systemDynamicFromField->getTmpSystemFieldList($fid);
        }

        if (count($fieldData) == 1){
            if (empty($fieldData[0])){
                $fieldData = $systemDynamicFromField->getTmpSystemFieldList($fid);
            }
        }

        //删除已经设置过权限的系统字段
        foreach ($fieldData as $k => $fieldDatum) {
            if ($systemFieldModel->getFieldIdData($fieldDatum['id'])){
                unset($fieldData[$k]);
            }
        }

        return $fieldData;
    }

    /**
     * 获取账号对应部门
     */
    public function getWhere($power,$udata): array
    {
        $where = [];
        $systemService = new System();
        $orgModel = new UserOrganization();
        $list = $orgModel->getStructureIdPersonIdModel();
        $department_ids = $systemService->getParentIdStr($udata['department_id']['id'],$list);
        $department_ids = explode(',',rtrim($department_ids,','));

        switch ($power){
            case 1:
                break;
            case 3:
                $department_ids = $systemService->getOrgIdStr($udata['department_id']['id'],$list);
//                $department_ids = $systemService->getOrgIdStr($orgId,$orgModel->getStructure ());
//                unset($department_ids[count ($department_ids)-1]);
                $where[] = ['department_id','in',$department_ids];
                $where[] = ['type','=',0];
                break;
            case 2:
                //获取分公司ID
                $orgId = $systemService->getOrgFgsId($udata['department_id']['id']);
                $department_ids = $systemService->getOrgIdStr($orgId,$list);
//                unset($department_ids[count ($department_ids)-1]);
                $where[] = ['department_id','in',$department_ids];
                $where[] = ['type','=',0];
                break;
            case 4:
                $where['id'] = $udata['id'];
                break;
        }
        return $where;
    }

    /**
     * 返回登录用户logo
     * @param $userData
     * @return string
     */
    public function getUserLogo($userData)
    {
        $path = '/storage/';
        $type = $userData['type'];
        // 获取默认logo
        $default_logo = $this->getDefaultLogo();
        if($type == UserModel::LEVEL_ZERO){
            //获取系统是否存在分支 如果不存在返回默认logo
            $branch_department_ids = $this->getBranchDepartmentIds();
            if(empty($branch_department_ids)){
                $logo = $default_logo;
            }else{
                //判断登录人员直属部门是否绑定分支 如果绑定返回分支logo 否则返回默认logo
//                $info = $this->getDepartmentBranch($userData['department_id']['id']);
//                $logo = $info && $info['logo'] ? $path.$info['logo'] : $default_logo;
                $logo = $this->getBranchLogo($userData['department_id']['id']);
            }
        }elseif($type == UserModel::LEVEL_ONE || $type == UserModel::LEVEL_TWO){
            //登录人为admin || 总公司账号 返回默认logo
            $logo = $default_logo;
        }else{
            //登录账号为分支账号  判断该账号是否存在logo 如果不存在 返回默认logo 否则返回该账号的logo
            $logo = $userData['logo'] ? $path.$userData['logo'] : $default_logo;
        }
        if(!$logo){
            $logo = $default_logo;
        }
        return  config('file.url').'/'.$logo;
    }

    public function getUserEnterName($userData)
    {
        $type = $userData['type'];
        // 获取默认logo
        $default_enter_name = $this->getDefaultEnterName();
        if($type == UserModel::LEVEL_ZERO){
            //获取系统是否存在分支 如果不存在返回默认logo
            $branch_department_ids = $this->getBranchDepartmentIds();
            if(empty($branch_department_ids)){
                $enter_name = $default_enter_name;
            }else{
                //判断登录人员直属部门是否绑定分支 如果绑定返回分支logo 否则返回默认logo
//                $info = $this->getDepartmentBranch($userData['department_id']['id']);
//                $enter_name = $info && $info['enter_name'] ? $info['enter_name'] : $default_enter_name;
                $enter_name = $this->getBranchEnterName($userData['department_id']['id']);
            }
        }elseif($type == UserModel::LEVEL_ONE || $type == UserModel::LEVEL_TWO){
            //登录人为admin || 总公司账号 返回默认logo
            $enter_name = $default_enter_name;
        }else{
            //登录账号为分支账号  判断该账号是否存在logo 如果不存在 返回默认logo 否则返回该账号的logo
            $enter_name = $userData['enter_name'] ? $userData['enter_name'] : $default_enter_name;
        }
        if(!$enter_name){
            $enter_name = $default_enter_name;
        }
        return $enter_name;
    }

    function getBranchEnterName($id){
        $info = \app\model\User::where('type',3)->where('department_id',$id)->find();
        if(!$info){
            //如果不存在 查找该部门上级是否是分支绑定部门
            $data = UserOrganization::where('id',$id)->field('parent_id')->find();
            if($data['parent_id'] != 0){
                return $this->getBranchEnterName($data['parent_id']);
            }
        }else{
            $default_enter_name = $this->getDefaultEnterName();
            return $info['enter_name'] ? $info['enter_name'] : $default_enter_name;
        }
    }

    function getBranchLogo($id){
        $path = '/storage/';
        $info = \app\model\User::where('type',3)->where('department_id',$id)->find();
        if(!$info){
            //如果不存在 查找该部门上级是否是分支绑定部门
            $data = UserOrganization::where('id',$id)->field('parent_id')->find()->toArray();
            if($data['parent_id'] != 0){
                return $this->getBranchLogo($data['parent_id']);
            }
        }else{
            $default_logo = $this->getDefaultLogo();
            return $info['logo'] ? $path.$info['logo'] : $default_logo;
        }
    }

    /**
     * 获取系统设置的分支
     * @return array
     */
    public function getBranchDepartmentIds()
    {
        $user = new UserModel();
        $list = $user->getBranchDepartmentIds();
        $department_ids = [];
        foreach($list as &$item){
            if($item['department_id']['id']){
                $department_ids[] = $item['department_id']['id'];
            }
        }
        return $department_ids;
    }

    /**
     * 获取该部门是否绑定了分支
     * @param $department_id
     * @return UserModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDepartmentBranch($department_id)
    {
        $info = UserModel::where('department_id',$department_id)
            ->where('type',UserModel::LEVEL_THREE)
            ->find();
        return $info;
    }

    public function getDefaultLogo()
    {
        $default_logo = branch::$default_logo;
        $info = UserModel::where('id',1)->field('logo')->find();
        if($info && $info['logo']){
            $default_logo = $info['logo'];
        }
        if($default_logo != branch::$default_logo){
            $default_logo = '/storage/'.$default_logo;
        }
        return $default_logo;
    }

    public function getDefaultEnterName()
    {
        $default_enter_name = branch::$default_enter_name;
        $info = UserModel::where('id',1)->field('enter_name')->find();
        if($info && $info['enter_name']){
            $default_enter_name = $info['enter_name'];
        }
        return $default_enter_name;
    }


    //获取uid的公司与部门
    public function getUidOrgTitle($uid)
    {
        $userModel = new \app\model\User();
        $orgModel = new UserOrganization();
        $systemService = new System();
        $userData = $userModel->getIdUserData ($uid);
        if (is_array ($userData['department_id'])){
            $oid = $userData['department_id']['id'];
        }else{
            $oid = $userData['department_id'];
        }
        $orgStr = '';
        $orgStr .= $orgModel->getStructureName($systemService->getOrgZgsId($oid)); //获取公司
        if ($oid){
            $orgStr .= $orgModel->getStructureName($oid); //获取用户部门
        }
        return $orgStr;
    }

    public function userIsLeaderUser($leader_user_id,$be_led_user_id)
    {
        if($leader_user_id == $be_led_user_id || !$be_led_user_id){
            return true;
        }
        //判断一个人是否为另一个人的领导
        $powerService = new Power();
        //获取领导人的数据可见范围
        $data_range = $powerService->getUserDataRand($leader_user_id);
        //判断数据可见范围是否是个人 个人返回false 否则判断该人员所在部门下是否包含被领导人 存在返回true  否则返回false
        if($data_range == 4){
            return false;
        }
        //获取领导人所在部门
        $userModel = new \app\model\User();
        $leader_user_department_id = $userModel->getUserDepartmentId($leader_user_id);
        //获取该部门下所有部门
        $systemService = new System();
        $orgModel = new UserOrganization();
        $department_ids = $systemService->getOrgIdStr($leader_user_department_id,$orgModel->getStructureIdPersonIdModel());

        $uidArr = $userModel->getDepartmentIdsUserIds ($department_ids);
        if(!in_array($be_led_user_id,$uidArr)){
            return false;
        }
        return true;
    }
}